﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using WorkFlowSystem.Common;
using WorkFlowSystem.DataBase;

namespace WorkFlowSystem.Business
{
    class LoginVerification
    {
        public static int Verifcation(string account, string password, ref int uid,ref int u_did, ref Authority auth) 
        {
            Logger.WriteLog("login verfication");
       
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() == -1)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接。");
                return -1;
            }
            else if (db_op.ConnectDB() == -2)
            {
                MessageBox.Show("请设置数据库连接。");
                return -1;
            }
            
            string sql = "select ul.uid, ul.u_auth,ui.u_did from user_login ul,user_info ui where " +
                "ul.u_account collate Chinese_PRC_CS_AS_WS =@u_account and ul.u_password collate Chinese_PRC_CS_AS_WS =@u_password and ui.uid = ul.uid ";
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@u_account", account));
            para_list.Add(new SqlParameter("@u_password", password));
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) <= 0)
            {
                MessageBox.Show("该账号不存在或密码输入错误。请重新登录。");
                return -1;
            }
            try
            {
                uid = int.Parse(dt.Rows[0]["uid"].ToString());
                u_did = int.Parse(dt.Rows[0]["u_did"].ToString());
            }
            catch (Exception ex) {
                Logger.WriteLog("ERROR:" + ex.Message);
            }
            string user_auth = dt.Rows[0]["u_auth"].ToString();
            
            if (user_auth == "USER")
                auth = Authority.USER;
            else if (user_auth == "MANAGER")
                auth = Authority.MANAGER;
            else if (user_auth == "BOSS")
                auth = Authority.BOSS;
            else if (user_auth == "ADMIN")
                auth = Authority.ADMIN;
            else
                auth = Authority.UNKNOW;
            return 0;
        }
    }
}
